﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using XISoft.AppCreator.Util.ConfigHelper.CodeConfig;
using XISoft.AppCreator.Util.ICodeCreator;
using XISoft.AppCreator.Util.Common;
using System.Windows.Forms;
using System.Collections;
using XISoft.AppCreator.TplEngine.Syntax;
using XISoft.AppCreator.TplEngine;
using XISoft.AppCreator.TplEngine.XITpl;
using XISoft.AppCreator.TplEngine.ITpl;

namespace XISoft.AppCreator.CreatorOpration
{
    public class CreatorAgent
    {
        private static readonly DataBaseInfo dbInfo=new DataBaseInfo();

        /// <summary>
        /// 从模型创建实体类
        /// </summary>
        /// <param name="EntityTable">模型实体表</param>
        /// <param name="languageType">语言选择</param>
        /// <returns></returns>
        public static String CreatEntity(DataTable EntityTable, String languageType)
        {
            IBaseEntity Entity = new XIEntity();
            Entity.EntityName = EntityTable.TableName.ToString();
            Entity.PropertyList = new List<IBaseProperty>();
            Entity.MethodList = new List<IBaseMethod>();

            foreach (DataRow edr in EntityTable.Rows)
            {
                IBaseType Type = new XIType();

                if (edr[ModelDataDictionary.EntityTable.Type].ToString() == "Attribute")
                {
                    IBaseProperty Property = new XIProperty();

                    Property.Name = edr[ModelDataDictionary.EntityTable.Name].ToString();
                    Type.Name = edr[ModelDataDictionary.EntityTable.DataType].ToString();
                    Property.Type = Type;
                    if (Boolean.Parse(edr[ModelDataDictionary.EntityTable.isPrimaryKey].ToString()))
                        Entity.PrimaryKey = Property;
                    else
                        Entity.PropertyList.Add(Property);
                    
                }
                else if (edr[ModelDataDictionary.EntityTable.Type].ToString() == "Method")
                {
                    IBaseMethod Method = new XIMethod();

                    Method.Name = edr[ModelDataDictionary.EntityTable.Name].ToString();
                    Type.Name = edr[ModelDataDictionary.EntityTable.DataType].ToString();
                    Method.Type = Type;
                    Entity.MethodList.Add(Method);
                }
            }

            if (Entity.PrimaryKey == null)
            {
                Entity.PrimaryKey = Entity.PropertyList[0];
                Entity.PropertyList.RemoveAt(0);
            }

            Hashtable var = new Hashtable();
            var.Add(TplEntry.CurrentEntity, Entity);

            CodeConfigElement codeConfig= CodeConfig.GetConfigSetting(languageType);
            StringBuilder filePath = new StringBuilder(Application.StartupPath)
            .Append("\\code\\temp\\")
            .Append(codeConfig.FileName)
            .Append(Entity.EntityName)
            .Append(".")
            .Append(codeConfig.Extension);

            ReadTpl readTpl = new ReadTpl(Application.StartupPath +"\\tpls\\"+ codeConfig.EntityTpl);
            readTpl.init();
            readTpl.Variables = var;
            readTpl.run();
            readTpl.WriteFile(filePath.ToString());
            return filePath.ToString();
            
        }
        /// <summary>
        /// 数据库创建实体
        /// </summary>
        /// <param name="strTable">表名</param>
        /// <param name="strNameSpace">实体类命名空间</param>
        /// <param name="languageType">语言选择</param>
        /// <returns></returns>
        public static String CreatEntity(String strTable, String strNameSpace, String languageType)
        {
            String szPath = String.Empty;
            try
            {
                StringBuilder tmp = new StringBuilder(Application.StartupPath)
                .Append("\\code\\temp\\")
                    .Append(CodeConfig.GetConfigSetting(languageType).FileName);

                CreateDirectory(tmp.ToString());

                szPath = tmp.Append(strTable)
                    .Append(".")
                    .Append(CodeConfig.GetConfigSetting(languageType).Extension)
                    .ToString();

                ICreateEntity createEntry = CodeConfig.GetConfigSetting(languageType).GetEntityCreator();
                if (createEntry == null) throw new Exception("配置文件有错误");
                createEntry.SetEntityName(strTable);
                createEntry.CreateNameSpace(strNameSpace);

                DataTable table = dbInfo.GetTableDictionary(strTable);

                int nId = -1;
                foreach (DataRow row in table.Rows)
                {
                    if (nId == (int)row["Id"]) continue;
                    nId = (int)row["Id"];
                    createEntry.CreateProperty(row["Type"].ToString(), row["Name"].ToString());
                }

                createEntry.WriteFile(szPath);
            }
            catch (Exception e)
            {
                LogHelper.Trace(e);
            }
            return szPath;
        }
        public static String CreateDataLayer(String strTable, String strNameSpace, String languageType)
        {
            String szPath = String.Empty;
            try
            {
                StringBuilder tmp = new StringBuilder(Application.StartupPath)
                .Append("\\code\\temp\\")
                    .Append(CodeConfig.GetConfigSetting(languageType).FileName);

                CreateDirectory(tmp.ToString());


                szPath = tmp.Append(strTable)
                    .Append("DAO.")
                    .Append(CodeConfig.GetConfigSetting(languageType).Extension)
                    .ToString();

                ICreateDataLayer createDataLayer = CodeConfig.GetConfigSetting(languageType).getDataLayerCreator();


                createDataLayer.CreateNameSpace(strNameSpace);
                createDataLayer.SetEntityName(strTable);
                createDataLayer.SetEntityInfo(dbInfo.GetTableDictionary(strTable));
                createDataLayer.CreateAddMethod();
                createDataLayer.CreateDeleteMethod();
                createDataLayer.CreateGetModelMethod();
                createDataLayer.CreateUpdateMethod();
                createDataLayer.CreateExistsMethod();
                createDataLayer.CreateGetModelListMethod();// (strTable, szPath, strNameSpace);
                createDataLayer.WriteFile(szPath);
            }
            catch (Exception e)
            {
                LogHelper.Trace(e);
            }
            return szPath;
        }

        public static void CreateSql(DataSet ds, String szPath, String languageType)
        {
        }
        private static void CreateDirectory(String szPath)
        {
            if (!Directory.Exists(szPath))
            {
                Directory.CreateDirectory(szPath);
            }
        }
    }
}
